<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Account/classes/PhpFox_ComponentSignup.class.php, $Author:  $ */



/** Component for display login form and processing login action.
 *
 * Parameters:
 *  1. url_verify - logical name of verify page
 *
 * @package module.account
 * @version $Id: PhpFox_ComponentSignup.class.php 491 2008-09-22 10:39:40Z phpfoxsv $
 *
 */
class PhpFox_Mod_Account_ComponentSignup extends BaseComponent
{

    /** Processing method
     */
	function process()
	{
		if (App::getUser('user'))
		{
			App::gotoUrl('public');
		}
		
		$oSrvCf = &App::getModuleService('Account', 'CustomField');

	    $bSignupPic = App::getSetting('singup_pic_upload');

		$oSrvSec = &App::getModuleService('Account', 'Security');
		
	   	$this->oDatabase->_delete(App::getT('captcha'), "time < " . (time() - 10 * 60));

		//validator
		$aFields = array(
			'aUser[user]'      => array('title'=>App::format('username'), 'pattern'=>'/^[a-zA-Z0-9_\-]{'. App::getParam('core','user_min') .',30}$/', 'message' => str_replace(array("6","30"), array(App::getParam('core','user_min'), App::getParam('core','user_max')), App::format('Mod_Account.error.check_username'))),
			'aUser[email]'     => array('title'=>App::format('e_mail'),   'def'=>'email'),
			'aUser[gender]'    => array('title'=>App::format('gender'),   'def'=>'required'),			
			'aUser[location]'  => array('title'=>App::format('location'), 'def'=>'required'),
			'aBirthDate_Day' => array('title'=>App::format('date_of_birth_164') . ' (' . App::format('Mod_Account.day') . ')', 'def'=>'required'),
			'aBirthDate_Month' => array('title'=>App::format('date_of_birth_164') . ' (' . App::format('Mod_Account.month') . ')', 'def'=>'required'),
			'aBirthDate_Year' => array('title'=>App::format('date_of_birth_164') . ' (' . App::format('Mod_Account.year') . ')', 'def'=>'required','min'=>App::getSetting('birthdate_year_min'),'max'=>App::getSetting('birthdate_year_max')),
			'pass'             => array('title'=>App::format('password'),             'def'=>'password'),
			'pass2'            => array('title'=>App::format('confirm_password'),     'def'=>'password'),
    		'agree'            => array('title'=>'Agree','def'=>'required', 'message'=>App::format('Mod_Account.error.must_agree')),
		);

        $aStates = array();
		if (App::getSetting('us_states'))
        {
            $aFields['aUser[zip]']   = array('title' => App::format('zip'),   'def' => 'zip_us');
            $aFields['aUser[state]'] = array('title' => App::format('state'), 'def' => 'required');
            foreach (App::getTxtFile('us_stat.txt', true) as $sState)
            {
                $aStates[$sState] = $sState;
            }
        }

		$aRules = array(
		    array('pass', 'pass2', '=='),
		);

		$oValidator = &App::newObject('Validator', $aFields, $aRules);
		/* @var $oValidator Validator */

		$bIsProtImage = App::getSetting('signup_image');

		$oAcc = $this->_oModule->getItem('Account');
		$bProcessed = false;
		$oReq = &App::getRequest();


		if ( $iReferId = $oReq->get('refid') )
		{
			$this->_oModule->setSessVar('refid', strip_tags($iReferId));
			App::gotoUrl('public.signup');
		}

		$sEmail = '';
		switch($oReq->getAction())
		{
			case 'signup':
				
				$oSrvSec->csrfCheck();
				
			    //fill in user data
				$oAcc->aData = $oReq->getArray('aUser');
				$oAcc->aData['password']  = md5($oReq->get('pass'));
				$oAcc->aData['day']       = $oReq->getInt('aBirthDate_Day');
				$oAcc->aData['month']     = $oReq->getInt('aBirthDate_Month');
				$oAcc->aData['year']      = $oReq->getInt('aBirthDate_Year');
				$oAcc->aData['signup_ip'] = $_SERVER['REMOTE_ADDR'];
				$oAcc->aData['lang_file'] = $oReq->get('lang_file');

			    //remove zip and states validation for non-USA
                if (App::getSetting('us_states'))
                {
                    if ($oAcc->aData['location'] != 'United States')
                    {
                        unset($oValidator->aFields['aUser[zip]']);
                        unset($oValidator->aFields['aUser[state]']);
                    }
                }

				/* @var $oSrvSec PhpFox_Mod_Account_ServiceSecurity */
				$oBanService = &App::getModuleService('Site', 'Ban');
                /* @var $oBanService PhpFox_Mod_Site_ServiceBan */

                if ( !eregi("[a-z]", substr($oAcc->aData['user'], 0, 1)) )
                {
                	$this->addErrors(App::format('Mod_Account.first_must'));
                }
			    if (!$oValidator->isValid($oReq->getAll()))
				{
					$this->addErrors($oValidator->getErrors());
				}
				if (in_array(strtolower($oAcc->aData['user']), $oBanService->getBlockedLogins()))
				{
				    $this->addErrors(App::format('Mod_Site.info.username_banned'));
				}
				if( !$oBanService->checkDirs($oAcc->aData['user']) )
				{
					$this->addErrors(App::format('Mod_Site.info.username_banned'));
				}
				if (in_array($oAcc->aData['user'], App::getParam('url.reserved_names')))
				{
				    $this->addErrors(App::format('Mod_Site.info.username_banned'));
				}
				if (!$oBanService->checkEmail($oAcc->aData['email']))
				{
				    $this->addErrors(App::format('Mod_Site.info.email_banned'));
				}
 				if ($bIsProtImage && !$oSrvSec->checkProtectionCode($oReq->get('sProtCode')))
			    {
			        $this->addErrors(App::format('Mod_Account.error.wrong_code'));
			    }
			    if ($bSignupPic && $bSignupPic != '2' && !$this->_checkImage('user_pic'))
        		{
    	        	$this->addErrors(App::format('Mod_Account.error.must_upload_pic'));
        		}
				if ((! $this->getErrors()) && $bSignupPic && $this->_checkImage('user_pic'))
                {
                    $this->_uploadPic($oAcc, 'user_pic');
                }

 				if (! $this->getErrors())
 				{
					$oSrvAcc = &App::getModuleService('Account', 'Account');
					/* @var $oSrvAcc PhpFox_Mod_Account_ServiceAccount */

					if ( ( $iAccountId = $oSrvAcc->create($oAcc, $this->getParam('url_verify', 'public.verify'), $this->_oModule->getSessVar('refid'))) )
					{
						$aFields = $oReq->getArray('field_option');
						$aFieldsText = $oReq->getArray('text_option');

						if ( $iAccountId )
						{
							$oSrvCf->updateProfileSettings($aFields, $aFieldsText, $iAccountId);
						}

						if ( App::pluginInstalled('vbulletin') )
						{
							$sUrl = App::getSetting('header_location');
							if ( empty($sUrl) )
                            {
                            	$sUrl = 'public.account';
                            }
							$_SESSION['redirect_url'] = $sUrl;
							App::gotoUrl('public.login', array('new' => 'account', 'verify' => (App::getSetting('signup_email') ? 'yes' : 'no')));
						}

					    //send email
					    $sEmail     = $oAcc->aData['email'];
					    $bProcessed = true;
					    if (!App::getSetting('signup_email'))
					    {
					        //performs login and forward to picture upload
                            $oSrvSec->login($oAcc->aData['user'], $oReq->get('pass'));
                            $sUrl = App::getSetting('header_location');
                            if ( empty($sUrl) )
                            {
                            	$sUrl = 'public.account';
                            }
                            if (strpos($sUrl, '://') === false)
                            {
                            	$sUrl = App::makeUrl($sUrl);
                            }
                            App::forward($sUrl);
					    }
					}
					else
					{
					    $this->addErrors($oSrvAcc->getErrors());
					}
 				}
				break;
		}

		if (!isset($oAcc->aData['year']))
		{
		    $oAcc->aData['year'] = 0;
		}
		if (!isset($oAcc->aData['month']))
		{
		    $oAcc->aData['month'] = 0;
		}
		if (!isset($oAcc->aData['day']))
		{
		    $oAcc->aData['day'] = 0;
		}

		$oTpl = &$this->_oModule->getTemplate();
		$oTpl->assign(array(
		    'aErrors'      => $this->getErrors(),
			'aUser'        => $oAcc->aData,
			'dtBirthdate'  => $oAcc->aData['year'] . '-' . $oAcc->aData['month'] . '-' . $oAcc->aData['day'],
            'bZipState'    => App::getSetting('us_states'),
		    'iStartYear'   => App::getSetting('birthdate_year_min'),
		    'iEndYear'     => App::getSetting('birthdate_year_max'),
		    'bSignupPic'   => $bSignupPic,
		    'bProcessed'   => $bProcessed,
			'sEmail'       => $sEmail,
		    'bIsProtImage' => $bIsProtImage,
		    'aStates'      => $aStates,
		    'sAgreeUrl' => App::makeUrl('public.popup',array('file'=>'terms','dir'=>'language')),
		    'sLangFile' => App::getLang(),
		    'bAllowLangPack' => App::getSetting('allow_change_lang'),
		    'aCustom' => $oSrvCf->getSignupFields(),
		    'sSignupErrors' => App::format('Mod_Account.signup.errors'),
		    'aGenders' => App::getOptions('gender'),
		    'aCountries'   => App::getOptions('country', true),
		    'iUserMax' => App::getParam('user_max'),
		    'iPasswordMax' => App::getParam('password_max')
		));

		$oTpl->assignSrc(array(
		    'jsValidation' => $oValidator->makeJS(),
		    'jsValMess'    => $oValidator->makeJsMess(),
		    'csrfInput' => $oSrvSec->csrfInput()
		));
		$srcHtml = $oTpl->fetch('Signup.html');
		return $srcHtml;
	}


	/** Check uploaded image
	 */
	function _checkImage($sField)
	{
	    return (isset($_FILES[$sField]) && getimagesize($_FILES[$sField]['tmp_name']));
	}

	/** Upload picture
	 */
	function _uploadPic($oAcc, $sFeldName)
	{
        $oImage = &App::newObject('file_Image');
        /* @var $oImage file_Image */

        $sPicPath = App::getParam('user.pic.path');
        if ($oImage->upload($sFeldName, $sPicPath, $oAcc->aData['user'], 'jpg'))
        {
			$oImage->loadInfo($sPicPath.$oAcc->aData['user'].(isset($iImageId) ? $iImageId : '').'.jpg');
            $oImage->_checkLimits();
            $this->addErrors($oImage->getErrors());
            if (!count($this->getErrors()))
            {
            	//make thumbnails
            	foreach(App::getParam('user.pic.sizes') as $iSize)
            	{
                	$oImage->makeThumbnail($sPicPath.$oAcc->aData['user'].'_'.$iSize.'.jpg', $iSize, $iSize);
            	}
            	
            	if(!App::getParam('bSaveOriginalImages'))
                {
                	unlink($sPicPath . $oAcc->aData['user'].'.jpg');
                }
	                    
            	return true;
			}else
			{
                return false;
            }
        }
        else
        {
            $this->addErrors($oImage->getErrors());
        }

        return false;
	}

}
?>